package com.shengwei.truck.driver.view.ui.mine.userinfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import androidx.lifecycle.Observer;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.JsonLoginData;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.databinding.ActivityLoginBinding;
import com.shengwei.truck.driver.third_sdk.jpush.TagAliasOperatorHelper;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.MainActivity;
import com.shengwei.truck.driver.view.ui.settings.ModifyPwdActivity;
import com.shengwei.truck.driver.vm.LoginViewModel;

import org.slf4j.spi.MDCAdapter;

import java.lang.ref.WeakReference;
import static com.shengwei.truck.driver.third_sdk.jpush.TagAliasOperatorHelper.ACTION_SET;
import static com.shengwei.truck.driver.third_sdk.jpush.TagAliasOperatorHelper.sequence;


/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity<LoginViewModel, ActivityLoginBinding> implements View.OnClickListener {
    private String mUsername;
    private String mPassword;
    private String TAG = "LoginActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        User user = User.getInstance(getApplicationContext());
        String token = user.getToken();
        MyLogCat.i(TAG,"token="+token);
        //如果曾登录过，则直接跳转到首页
        if(!TextUtils.isEmpty(token)) {
           Intent i = new Intent(LoginActivity.this, MainActivity.class);
           startActivity(i);
           finish();
           return;
        }
        getLastIntent();
        //使用Android JetPack架构组件中的 “liveData”监听数据的变化，一旦有变化则让UI显示这些数据——观察者模式。
        initLiveDataObersve();
    }

    /**
     * 获取上页传递过来的数据
     */
    public void getLastIntent() {
        mDataBinding.setUsername(mUsername);
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mUsername = bundle.getString("username");
            mDataBinding.setUsername(mUsername);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }


    /**
     * 初始化用户名文本框
     */
    public void initEditUserName() {

        //眼睛，叉号
        mDataBinding.edtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length() > 0){
                    //显示×号
                    //gxw-可能要恢复mDataBinding.imvClearUserName.setVisibility(View.VISIBLE);
                    if (mDataBinding.edtPassword.getText().toString().length() >0) {
                        mDataBinding.btLogin.setEnabled(true);
                    }
                    else {
                        //gxw-可能要恢复 mDataBinding.btLogin.setEnabled(false);
                    }
                }
                else{
                    //gxw-可能要恢复 mDataBinding.btLogin.setEnabled(false);
                    //gxw-可能要恢复m mDataBinding.imvClearUserName.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        //用户名框获得焦点后，隐藏密码框的  清除文本按钮
        mDataBinding.edtUsername.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isFocus) {
                if(isFocus) {
                    //gxw-可能要恢复 mDataBinding.imvClearPwd.setVisibility(View.GONE);
                    //gxw- 可能要恢复 if(mDataBinding.edtUsername.getText().toString().length() > 0){}
                    //gxw-可能要恢复  mDataBinding.imvClearUserName.setVisibility(View.VISIBLE);
                }

            }
        });

        return;
    }


    /**
     * 初始化密码文本框
     */
    private void initEditPassword() {
        //监听密码文本框的文字改变
        mDataBinding.edtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if ( mDataBinding.edtPassword.length() > 0) {
                    mDataBinding.edtPassword.requestFocus();
                    //gxw-可能要恢复 mDataBinding.imvClearPwd.setVisibility(View.VISIBLE);

                    if (mDataBinding.edtUsername.getText().toString().length() > 0) {
                        mDataBinding.btLogin.setEnabled(true);
                    }
                    else {
                        //gxw-可能要恢复 mDataBinding.btLogin.setEnabled(false);
                    }
                } else {
                    //gxw-可能要恢复mDataBinding.btLogin.setEnabled(false);
                    //gxw-可能要恢复  mDataBinding.imvClearPwd.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //密码框获得焦点后，隐藏用户名框的  清除文本按钮
        mDataBinding.edtPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isFocus) {

           /*gxw-s 可能以后要恢复    if(isFocus) {
                    mDataBinding.imvClearUserName.setVisibility(View.GONE);
                    if(mDataBinding.edtPassword.getText().toString().length() > 0)
                        mDataBinding.imvClearPwd.setVisibility(View.VISIBLE);
                }gxw-e*/

            }
        });
        //显示和隐藏密码
        mDataBinding.checkShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //CheckBox选中，显示明文
                    mDataBinding.edtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mDataBinding.checkShowPwd.setBackgroundResource(R.drawable.open_eye);
                } else {
                    //CheckBox取消选中，显示暗文
                    mDataBinding.edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mDataBinding.checkShowPwd.setBackgroundResource(R.drawable.close_eye);
                }
                //光标移至最末端
                mDataBinding.edtPassword.setSelection(mDataBinding.edtPassword.getText().toString().length());
            }
        });
    }

    /**
     * 初始化UI控件
     */
    private void initView() {
       // setToolBar(false, false, R.string.login);
        mDataBinding.btLogin.setEnabled(true);
        mDataBinding.tvForgetPwd.setOnClickListener(this);
        mDataBinding.tvRegist.setOnClickListener(this);

        //去登录
        mDataBinding.btLogin.setOnClickListener(this);
        mDataBinding.imvClearUserName.setOnClickListener(this);

        //初始化用户名文本框
        initEditUserName();
        //初始化密码文本框
        initEditPassword();
    }



    /**
     * 检查用户输入的字段是否合法
     * @return boolean : true合法，false不合法
     */
    public boolean checkInput()
    {
        boolean isCorrect = true;
        WeakReference<Context> weakReferenceContext = new WeakReference<>(LoginActivity.this);
        //验证手机号
        isCorrect = CommonUtil.checkMobile(mUsername,weakReferenceContext,true);

        //验证密码格式
        if(isCorrect) {
            isCorrect = CommonUtil.checkPassword(mPassword,weakReferenceContext,0);    //检查密码
        }
        return isCorrect;
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {

        //登录成功时，监听登录接口返回的数据
        mViewModel.getJsonLogin().observe(this, new Observer<Result<JsonLoginData>>() {
            @Override
            public void onChanged(Result<JsonLoginData> result) {

                result.handler(new OnCallback<JsonLoginData>() {
                    @Override
                    public void onSuccess(JsonLoginData data) {
                        String username = data.getUsername();
                        String userId = data.getUserId();
                        setJpushAlia(userId);
                        MyLogCat.i(TAG,"alia="+userId);
                        Intent i = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(i);
                    }
                });
            }
        });
    }
    /**
     * 清空控件文本
     */
    private void clearText(EditText edit) {
        edit.setText("");
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imvClearUserName:
                clearText(mDataBinding.edtUsername);
                break;
            case R.id.imvClearPwd:
                clearText(mDataBinding.edtPassword);
                break;
            case R.id.tvRegist:
                Intent i = new Intent(LoginActivity.this,RegistActivity.class);
                startActivity(i);
                break;
            case R.id.tvForgetPwd:
                mUsername = mDataBinding.edtUsername.getText().toString();
                boolean isMobile = CommonUtil.checkMobile(mUsername, new WeakReference<>(this),false);

                Intent intentForgetPwd = new Intent(LoginActivity.this, ModifyPwdActivity.class);
                intentForgetPwd.putExtra("fromPage", MyConstant.FORGET_PASSWORD); //忘记密码

                //如果是手机号，则直接传递到“忘记密码”页面去，用于获取短信码
                if(isMobile) {
                    intentForgetPwd.putExtra("mobileNum", mUsername); //忘记密码
                }
                startActivity(intentForgetPwd);
                break;
            case R.id.btLogin:
                mUsername = mDataBinding.edtUsername.getText().toString();
                mPassword = mDataBinding.edtPassword.getText().toString();

                //检查输入是否正确
                boolean isInputCorrect = checkInput();
                //VM层去调遣Model层（Repository+DataSource）获取数据
                if(isInputCorrect) {
                    mViewModel.login(mUsername, mPassword);
                }
                break;
        }
    }


    /**
     * 设置别名
     * @param alia
     */
    public void setJpushAlia(String alia) {
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = ACTION_SET;
        sequence++;
        tagAliasBean.alias = alia;
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(),sequence,tagAliasBean);
    }
}